<template>
  <el-dialog :title="title" :visible.sync="open" width="100%" append-to-body :close-on-click-modal="false"
             v-dialogDrag>
    <div class="app-container">
      <el-row :gutter="10">
        <el-col :span="4">
          <el-card class="box-card">
            <div>
              <el-form ref="form" size="small" :model="form" :rules="rules" :inline="true">
                <el-row>
                  <el-col :span="24">
                    <el-form-item label="到货类型:" prop="fahuoType">
                      <el-select v-model="form.fahuoType" placeholder="请选择到货类型" clearable>
                        <el-option v-for="dict in dict.type.zhifahuo_type"
                                   :key="dict.value" :label="dict.label" :value="dict.value"/>
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col :span="24">
                    <el-form-item label="过磅吨位:" prop="dunwei">
                      <el-input-number v-model="form.dunwei" :precision="4" style="width: 150px;"/>
                    </el-form-item>
                  </el-col>
                  <el-col :span="24">
                    <el-form-item label="到货总价:" prop="daohuoMoney">
                      <el-input-number v-model="form.daohuoMoney" :precision="2" style="width: 150px;" disabled/>
                    </el-form-item>
                  </el-col>
                  <el-col :span="24">
                    <el-form-item label="到货时间" prop="arrivalDate">
                      <el-date-picker clearable
                                      v-model="form.arrivalDate"
                                      type="datetime"
                                      value-format="yyyy-MM-dd HH:mm:ss"
                                      placeholder="请选择到货日期">
                      </el-date-picker>
                    </el-form-item>
                  </el-col>
                  <el-col :span="24">
                    <el-form-item label="运费:" prop="yunfei">
                      <el-input-number v-model="form.yunfei" :precision="2" style="width: 150px;"/>
                    </el-form-item>
                  </el-col>
                  <el-col :span="24">
                    <el-form-item label="送货人:" prop="songhuoid">
                      <el-select v-model="form.songhuoid" placeholder="请选择送货人" filterable @change="selectSonghuo">
                        <el-option v-for="dict in dict.type.goods_people" ref="myselectSonghuo"
                                   :key="dict.value" :label="dict.label" :value="dict.value"/>
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col :span="24">
                    <el-form-item label="电话:" prop="songhuotel">
                      <el-input v-model="form.songhuotel"></el-input>
                    </el-form-item>
                  </el-col>
                  <el-col :span="24">
                    <el-form-item label="开户行:" prop="songkaihuhang">
                      <el-input v-model="form.songkaihuhang"></el-input>
                    </el-form-item>
                  </el-col>
                  <el-col :span="24">
                    <el-form-item label="账号:" prop="songzhanghao">
                      <el-input v-model="form.songzhanghao"></el-input>
                    </el-form-item>
                  </el-col>

                  <el-col :span="24">
                    <el-form-item label="备注:" prop="remark">
                      <el-input v-model="form.remark"></el-input>
                    </el-form-item>
                  </el-col>
                  <el-col :span="24">
                    <el-form-item label="直发货回执" prop="zhifahuo">
                      <file-upload v-model="form.zhifahuo" :limit="1"></file-upload>
                    </el-form-item>
                  </el-col>
                  <el-col :span="24">
                    <el-form-item label="过磅单" prop="guobangdan">
                      <image-upload v-model="form.guobangdan" :limit="1"></image-upload>
                    </el-form-item>
                  </el-col>
                </el-row>
              </el-form>
            </div>
          </el-card>
        </el-col>
        <el-col :span="20">
          <el-card class="box-card">
            <el-table border v-loading="loading" :data="goodsSalebuyallList" ref="table" :max-height="tableMaxHeight"
                      show-summary :summary-method="getSummaries">
              <el-table-column label="请购单号" align="center" prop="nos"/>
              <el-table-column label="订单单号" align="center" prop="projectNo"/>
              <el-table-column label="工程名称" align="center" prop="gongchengName" show-overflow-tooltip/>
              <el-table-column label="客户名称" align="center" prop="customerName" show-overflow-tooltip/>
              <el-table-column label="产品编码" align="center" prop="goodsCode"/>
              <el-table-column label="产品名称" align="center" prop="goodsName"/>
              <el-table-column label="产品型号" align="center" prop="goodModel"/>
              <el-table-column label="产品类型" align="center" prop="type" />
              <el-table-column label="采购数量" align="center" prop="shengyu"/>
              <el-table-column label="采购重量" align="center" prop="dun"/>
              <el-table-column label="已到货" align="center" prop="daohuoCount"/>
              <el-table-column label="剩余到货" align="center" prop="shengyuDaohuoCount"/>
              <el-table-column label="单价" width="150" fixed="right">
                <template slot-scope="scope">
                  <el-input-number v-model="scope.row.goodsBuyPrice" :precision="4" size="mini" :min="0"
                                   :disabled="scope.row.daohuoStatus == '2' ||  scope.row.tuihuoType == '8' || scope.row.tuihuoType == '9'"
                                   @change="calculateTotalPrice(scope.row)"
                  ></el-input-number>
                </template>
              </el-table-column>


              <el-table-column label="到货数量" width="150" fixed="right" prop="daohuoCountTemp">
                <template slot-scope="scope">
                  <el-input-number v-model="scope.row.daohuoCountTemp" :precision="8" size="mini" :min="0" :max="scope.row.shengyuDaohuoCount"
                                   :disabled="scope.row.daohuoStatus == '2' ||  scope.row.tuihuoType == '8' || scope.row.tuihuoType == '9'"
                                   @change="calculateTotalPrice(scope.row)"
                  ></el-input-number>
                </template>
              </el-table-column>

              <el-table-column label="到货吨位" width="150" fixed="right" prop="daohuoDunTemp">
                <template slot-scope="scope">
                  <el-input-number v-model="scope.row.daohuoDunTemp" :precision="8" size="mini" :min="0"
                                   :disabled="scope.row.daohuoStatus == '2' ||  scope.row.tuihuoType == '8' || scope.row.tuihuoType == '9'"
                                   @change="calculateTotalPrice(scope.row)"
                  ></el-input-number>
                </template>
              </el-table-column>

              <el-table-column label="到货金额" width="150" fixed="right" prop="daohuoMoney">
                <template slot-scope="scope">
                  <el-input-number v-model="scope.row.daohuoMoney" :precision="4" size="mini" :min="0"
                                   @change="calculateFromTotalPrice(scope.row)"
                  ></el-input-number>
                </template>
              </el-table-column>

              <el-table-column label="到货状态" align="center" prop="daohuoStatus">
                <template slot-scope="scope">
                  <dict-tag :options="dict.type.daohuo_status" :value="scope.row.daohuoStatus"/>
                </template>
              </el-table-column>
              <el-table-column align="center" label="成品/材料" prop="goodsType">
                <template slot-scope="scope">
                  <dict-tag :options="dict.type.goods_type" :value="scope.row.goodsType"/>
                </template>
              </el-table-column>
              <el-table-column align="center" class-name="small-padding fixed-width" label="操作" width="100"
                               fixed="right">
                <template slot-scope="scope">
                  <el-button size="mini" type="text" icon="el-icon-s-operation" @click="showDaohuoDetail(scope.row)">
                    到货明细
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
<!--            <div style="display: flex; align-items: center;">-->
              <!-- <div style="margin-left: 20px;">采购数量合计: {{ totalPurchaseCount }}</div>
              <div style="margin-left: 20px;">采购重量合计: {{ totalPurchaseWeight }}</div>
              <div style="margin-left: 20px;">已到货合计: {{ totalArrived }}</div>
              <div style="margin-left: 20px;">剩余到货合计: {{ totalRemainingArrival }}</div> -->
<!--              <div style="margin-left: auto;">本次到货合计: {{ form.daohuoMoney }}</div>-->
<!--            </div>-->
            <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum"
                        :limit.sync="queryParams.pageSize" @pagination="getList"/>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <div slot="footer" class="dialog-footer">
      <el-popconfirm :title="`确认到货吗？`" @confirm="handleDaohuo" style="margin-left: 10px;">
        <el-button slot="reference" type="primary">批 次 到 货</el-button>
      </el-popconfirm>

      <el-popconfirm :title="`确认全部到货吗？`" @confirm="handleAllDaohuo" style="margin:0 10px;">
        <el-button slot="reference" type="success">全 部 到 货</el-button>
      </el-popconfirm>
      <el-button @click="cancel">取 消</el-button>
    </div>

    <lv-daohuo-detail-list ref="daohuoDetailList" @ok="getList"></lv-daohuo-detail-list>
  </el-dialog>
</template>

<script>
import {getAction, addAction, getById, accAdd, accSub, accMul, accDiv, isEmpty} from '@/api/manage'
import LvDaohuoDetailList from "@/views/develop/lvDaohuoDetail/module/LvDaohuoDetailList";
import {parseTime} from "@/utils/common";

export default {
  name: "DaohuoForm",
  dicts: ['goods_people', 'zhifahuo_type', 'daohuo_status', 'goods_type'],
  components: {
    LvDaohuoDetailList,
  },
  data() {
    return {
      title: "到货1处理",
      open: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      rows: [],
      rules: {
        fahuoType: [
          {required: true, message: "请选择到货类型", trigger: "blur"}
        ],
        arrivalDate: [
          {required: true, message: "请选择到货时间", trigger: "blur"}
        ],
        dunwei: [
          {required: true, message: "请输入吨位", trigger: "blur"}
        ],
        yunfei: [
          {required: true, message: "请输入运费", trigger: "blur"}
        ],

      },
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      caigoudanId: null,
      goodsId: null,
      projectId: null,
      // 销售信息管理表格数据
      goodsSalebuyallList: [],
      form: {
        dunwei: null,
        arrivalDate: null,
        guobangdan: null,
        daohuoMoney: 0.00,
        yunfei: null,
        songhuoid: null,
        songhuoren: null,
        songhuotel: null,
        songkaihuhang: null,
        songzhanghao: null,
        remark: null,
      },
      // 查询参数
      queryParams: {
        cgallid: null,
        pageNum: 1,
        pageSize: 20,
        mainId: null,
        name: null,
        brand: null,
        unit: null,
        costPrice: null,
        count: null,
        cost: null,
        validityTerm: null,
        buyId: null,
        buyName: null,
        buyDate: null,
        buyType: null,
        reimburse: null,
        supplierId: null,
        supplierName: null,
        dateRange: "",
        pageSizeZero:"true",
        params: {},
      },
      url: {
        list: '/goodsSalebuyall/goodsSalebuyall/list',
        daohuoAdd: '/lvDaohuo/lvDaohuo/add',
        daohuoAddAll: '/lvDaohuo/lvDaohuo/daohuoAddAll',
        goodsPeopleById: '/goodsPeople/goodsPeople/',
        goodsAllArrived: '/goodsSalebuyall/goodsSalebuyall/goodsAllArrived',
        tuihuoBuruku: '/goodsSalebuyall/goodsSalebuyall/tuihuoBuruku',
        tuihuoRuku: '/goodsSalebuyall/goodsSalebuyall/tuihuoRuku',
      },
      tableMaxHeight: window.innerHeight - 320,
      totalPurchaseCount: 0,
      totalPurchaseWeight: 0,
      totalArrived: 0,
      totalRemainingArrival: 0,
      totalCurrentArrival: 0,
    };
  },
  created() {
    this.reset();
    window.addEventListener('resize', this.getTableHeight);
  },
  destroyed() {
    window.removeEventListener('resize', this.getTableHeight);
  },
  methods: {
    accMul,
    getSummaries(param) {
      // console.log(param);
      const {columns, data} = param;
      const sums = [];

      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = "合计";
          return;
        }
        const values = data.map((item) => Number(item[column.property]));
        // 只合计amount1和amount3，想合并哪些列就在这里指定
        if (column.property === "shengyu"
          || column.property === 'dun'
          || column.property === 'daohuoMoney'
          || column.property === 'daohuoCountTemp'
          || column.property === 'daohuoDunTemp'
          || column.property === 'daohuoDun'
          || column.property === 'daohuoCount'
          || column.property === 'shengyuDaohuoCount'
          ) {

          sums[index] = values.reduce((prev, curr) => {
            const value = Number(curr);
            if (!isNaN(value)) {
              return accAdd(prev, curr);
            } else {
              return prev;
            }
          }, 0);
        }
      });
      return sums;
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        dunwei: null,
        arrivalDate: null,
        guobangdan: null,
        daohuoMoney: 0.00,
        yunfei: null,
        songhuoid: null,
        songhuoren: null,
        songhuotel: null,
        songkaihuhang: null,
        songzhanghao: null,
        remark: null,
        fahuoType: "0",
      };
      this.resetForm("form");
    },
    selectSonghuo(value) {
      let that = this;
      that.$nextTick(() => {
        let arr = that.$refs.myselectSonghuo;
        for (let i = 0; i < arr.length; i++) {
          if (arr[i].currentValue == value) {
            that.form.songhuoren = arr[i].label;
            getById(this.url.goodsPeopleById, value).then(response => {
              that.form.songhuotel = response.data.songhuotel;//开户行
              that.form.songkaihuhang = response.data.songkaihuhang;//账号
              that.form.songzhanghao = response.data.songzhanghao;//行号
            });
          }
        }
      })
    },
    showDaohuoDetail(row) {
      let saleId = row.mainId;
      let goodId = row.goodsId;
      this.$refs.daohuoDetailList.showDaohuoDetailList(saleId, goodId);
    },
    getTableHeight() {
      this.tableHeight = window.innerHeight - 320
    },
    showdaohuo(row) {
      this.queryParams.mainId = row.id;
      this.form.buyId = row.id;
      this.form.yunfei = row.shippingFee;
      this.form.arrivalDate = parseTime(new Date(), '{y}-{m}-{d} {h}:{i}:{s}');
      this.open = true;
      this.getList();
    },
    handleDaohuo() {
      // 如果到货数量都为0，则不能提交
      // if (this.goodsSalebuyallList.every(item => item.daohuoCountTemp === 0)) {
      //   this.$modal.msgError("到货数量不能都为0");
      //   return;
      // }

      for (let i = 0; i < this.goodsSalebuyallList.length; i++) {
        if (isEmpty(this.goodsSalebuyallList[i].daohuoCountTemp)) {
          return this.$modal.msgError(this.goodsSalebuyallList[i].goodsName + "，到货数量不能为空");
        }
      }

      let that = this;
      that.$refs["form"].validate(valid => {
        if (valid) {
          that.form.goodsSalebuyallList = that.goodsSalebuyallList;
          addAction(that.url.daohuoAdd, that.form).then(response => {
            that.$modal.msgSuccess("到货成功");
            that.$emit('ok');
            that.reset();
            that.open = false;
          });
        }
      });
    },

    handleAllDaohuo() {
      // 如果到货数量都为0，则不能提交
      if (this.goodsSalebuyallList.every(item => item.daohuoCountTemp === 0)) {
        this.$modal.msgError("到货数量不能都为0");
        return;
      }
      let that = this;
      that.$refs["form"].validate(valid => {
        if (valid) {
          that.form.goodsSalebuyallList = that.goodsSalebuyallList;
          addAction(that.url.daohuoAddAll, that.form).then(response => {
            that.$modal.msgSuccess("到货成功");
            that.$emit('ok');
            that.reset();
            that.open = false;
          });
        }
      });
    },

    /** 查询销售信息管理列表 */
    getList() {
      this.loading = true;
      getAction(this.url.list, this.queryParams).then(response => {
        this.goodsSalebuyallList = response.rows;
        for (let i = 0; i < this.goodsSalebuyallList.length; i++) {
          this.goodsSalebuyallList[i].daohuoCountTemp = this.goodsSalebuyallList[i].shengyuDaohuoCount;
          this.goodsSalebuyallList[i].daohuoDunTemp = this.goodsSalebuyallList[i].shengyuDaohuoDun;
          if (isEmpty(this.goodsSalebuyallList[i].daohuoCountTemp)) {
            this.goodsSalebuyallList[i].daohuoCountTemp = 0;
          }
          if (isEmpty(this.goodsSalebuyallList[i].daohuoDunTemp)) {
            this.goodsSalebuyallList[i].daohuoDunTemp = 0;
          }

          console.log(this.goodsSalebuyallList[i].goodsBuyPrice + "--------" + this.goodsSalebuyallList[i].daohuoCountTemp)
          if (this.goodsSalebuyallList[i].goodsType === "0") {
              this.goodsSalebuyallList[i].daohuoMoney = this.goodsSalebuyallList[i].goodsBuyTotal;
          }
          if (this.goodsSalebuyallList[i].goodsType === "1") {
            this.goodsSalebuyallList[i].daohuoMoney =this.goodsSalebuyallList[i].goodsBuyTotal;
          }
        }
        this.total = response.total;
        this.loading = false;
        this.form.daohuoMoney = this.goodsSalebuyallList.reduce((total, item) => {
          return total + item.daohuoMoney;
        }, 0);
      });
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },

    calculateTotalPrice(row) {
      let that = this;
      if(row.goodsType==="0"){
        let daohuoMoney = accMul(row.goodsBuyPrice, row.daohuoCountTemp);
        that.$set(row, "daohuoMoney", daohuoMoney);
      }
      if(row.goodsType==="1"){
        let daohuoMoney = accMul(row.goodsBuyPrice, row.daohuoDunTemp);
        that.$set(row, "daohuoMoney", daohuoMoney);
      }
      this.form.daohuoMoney = this.goodsSalebuyallList.reduce((total, item) => {
        return accAdd(total,item.daohuoMoney);
      }, 0);
    },

    calculateFromTotalPrice(row) {
      this.form.daohuoMoney = this.goodsSalebuyallList.reduce((total, item) => {
        return accAdd(total,item.daohuoMoney);
      }, 0);

      let that = this;
      if (row.goodsBuyPrice && row.daohuoCountTemp) {
        if(row.goodsType==="0"){
          let goodsBuyPrice = accDiv(row.daohuoMoney, row.daohuoCountTemp);
          that.$set(row, "goodsBuyPrice", goodsBuyPrice);
        }
        if(row.goodsType==="1"){
          let daohuoDunTemp = accDiv(row.daohuoMoney, row.goodsBuyPrice);
          that.$set(row, "daohuoDunTemp", daohuoDunTemp);
        }
        that.$set(row, "daohuoMoney", daohuoMoney);
      }
      this.totalCurrentArrival = this.form.daohuoMoney;
    },



    goodsAllArrived(row) {
      let that = this;
      let params = {"id": row.id, "mainId": row.mainId};
      getAction(this.url.goodsAllArrived, params).then(response => {
        that.getList();
      });
    },

    goodsTuihuoBuruku(row) {
      let that = this;
      let params = {"id": this.queryParams.mainId};
      getAction(this.url.tuihuoBuruku, params).then(response => {
        that.getList();
      });
    },

    goodsTuihuoRuku(row) {
      let that = this;
      let params = {"id": this.queryParams.mainId};
      getAction(this.url.tuihuoRuku, params).then(response => {
        that.getList();
      });
    },

  }
};
</script>
